package com.example.eddie.test.activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.eddie.test.MyDatabases.MyDatabaseHelper;
import com.example.eddie.test.R;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class StudentActivity extends AppCompatActivity {

    private MyDatabaseHelper dbHelper;
    private SQLiteDatabase database;
    private List<String> list = new ArrayList<>();
    private MaterialEditText verification;
    private ImageView view, studentClass;
    private SweetAlertDialog sweetAlertDialog;
    private String SessionId,classID;

    private ArrayAdapter adapter;
    private LinearLayout yzm_Linear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        init();
        getImg();
        getClassName();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void init(){
        sweetAlertDialog = new SweetAlertDialog(this,SweetAlertDialog.PROGRESS_TYPE).setTitleText("拼命加载中~");
        yzm_Linear = (LinearLayout) findViewById(R.id.yzm_linear);
        dbHelper = new MyDatabaseHelper(this, "SearchInfo.db", null, 1);
        database = dbHelper.getWritableDatabase();
        verification = (MaterialEditText) findViewById(R.id.verification);
        view = (ImageView) findViewById(R.id.img_view);
        studentClass = (ImageView) findViewById(R.id.student_class);
        adapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, list);
        final Spinner spinner = (Spinner) findViewById(R.id.view_spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getName(spinner.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        spinner.setAdapter(adapter);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getImg();
            }
        });
    }

    public void get(View view) {
        sweetAlertDialog.show();
        getData(verification.getText().toString());
    }

    private void getData(final String yzm) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://59.79.112.9/ZNPK/KBFB_ClassSel_rpt.aspx");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setRequestMethod("POST");
                    connection.addRequestProperty("Referer", "http://59.79.112.9/ZNPK/KBFB_ClassSel.aspx");
                    connection.addRequestProperty("Cookie", SessionId);

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("Sel_XNXQ=20170&");
                    stringBuilder.append("Sel_XZBJ=+" + classID + "&");
                    stringBuilder.append("type=1&");
                    stringBuilder.append("txt_yzm=" + yzm);

                    OutputStream os = connection.getOutputStream();
                    os.write(stringBuilder.toString().getBytes());

                    InputStream is = connection.getInputStream();
                    BufferedReader bf = new BufferedReader(new InputStreamReader(is, "GB2312"));
                    final String s = bf.readLine();

                    if (!s.contains("验证码错误")) {
                        getClassImg();
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "wops～验证码错误！", Toast.LENGTH_SHORT).show();
                                getImg();
                                sweetAlertDialog.dismiss();
                                yzm_Linear.setVisibility(View.VISIBLE);

                            }
                        });
                    }
                    os.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getClassImg() {
        try {
            URL url = new URL("http://59.79.112.9/ZNPK/drawkbimg.aspx?type=1&w=1110&h=420&xn=2017&xq=0&bjdm=" + classID);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.addRequestProperty("Referer", "http://59.79.112.9/ZNPK/KBFB_ClassSel_rpt.aspx");
            connection.addRequestProperty("Cookie", SessionId);

            InputStream is = connection.getInputStream();
            final Bitmap bitmap = BitmapFactory.decodeStream(is);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    yzm_Linear.setVisibility(View.GONE);
                    studentClass.setVisibility(View.VISIBLE);
                    studentClass.setImageBitmap(bitmap);
                    sweetAlertDialog.dismiss();
                }
            });
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initClassName() {
        Cursor cursor = database.query("ClassNameInfo", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                if (cursor.getString(cursor.getColumnIndex("className")).length() < 8
                        && !cursor.getString(cursor.getColumnIndex("className")).contains("12")
                        && !cursor.getString(cursor.getColumnIndex("className")).contains("13")
                        && !cursor.getString(cursor.getColumnIndex("className")).contains("14")) {
                    list.add(cursor.getString(cursor.getColumnIndex("className")));
                }
            } while (cursor.moveToNext());
        }
        adapter.notifyDataSetChanged();
    }

    private void getClassName() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Document doc = Jsoup.connect("http://59.79.112.9/ZNPK/KBFB_ClassSel.aspx").timeout(5000).get();
                    Elements td = doc.select("option");
                    List<Element> listName = td.subList(0, td.last().elementSiblingIndex());
                    for (int i = 0; i < td.last().elementSiblingIndex(); i++) {
                        String className = listName.get(i).text();
                        List<String> list = serchDatabase();
                        if (!list.contains(className)) {
                            String classId = listName.get(i).attr("value");
                            ContentValues values = new ContentValues();
                            values.put("className", className);
                            values.put("classID", classId);
                            database.insert("ClassNameInfo", null, values);
                            values.clear();
                        }
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initClassName();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private List<String> serchDatabase(){
        List<String> list = new ArrayList<>();
        Cursor cursor = database.query("ClassNameInfo",null,null,null,null,null,null);
        if (cursor.moveToFirst()){
            do {
                String className = cursor.getString(cursor.getColumnIndex("className"));
                list.add(className);
            }while (cursor.moveToNext());
        }

        return list;
    }

    private void getImg() {
        new Thread(

                new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://59.79.112.9/sys/ValidateCode.aspx");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.addRequestProperty("Referer", "http://59.79.112.9/ZNPK/KBFB_ClassSel.aspx");

                    InputStream is = connection.getInputStream();
                    final Bitmap bitmap = BitmapFactory.decodeStream(is);
                    String headerField = connection.getHeaderField("set-cookie");
                    SessionId = headerField.split(";")[0];
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            view.setImageBitmap(bitmap);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getName(String name) {
        Cursor cursor = database.query("ClassNameInfo"
                , new String[]{"className,classID"}
                , "className like ?"
                , new String[]{name}
                , null, null, null);
        if (cursor.getCount()!=0){
            cursor.moveToFirst();
            classID = cursor.getString(cursor.getColumnIndex("classID"));
        }
    }
}
